<template>
	<view class="layout">
		<view class="top">
			<view class="search">
				<uv-input v-model="keyword" placeholder="输入关键词" prefixIcon="search"
					prefixIconStyle="font-size: 22px;color: #909399" shape="circle" border="surround"
					@focus="showSuggestions = true" @blur="handleInputBlur" @input="handleSearchInput"
					@confirm="handleSearch" @clear="clearKeyword" :maxlength="20" clearable>
					<template v-slot:suffix>
						<uv-button v-if="keyword" @click="handleSearch" :text="pageData.btn_text" type="default"
							size="small" iconColor="#eeeeee">搜索</uv-button>
					</template>
				</uv-input>
			</view>
			<!-- 建议列表 -->
			<view v-if="showSuggestions && suggestions.length" class="suggest-list">
				<view v-for="(item,index) in suggestions" :key="index" class="suggest-item"
					@click="selectKeyword(item)">
					{{ item }}
				</view>
			</view>
		</view>

		<view class="content">
			<!-- 关键字模块 -->
			<view v-if="!pageData.searchStatus">
				<view class="title">
					<text>历史搜索</text>
					<text class="clear-btn" @click="clearHistory">清空</text>

				</view>
				<view class="history-list">
					<uv-tags v-for="(item,index) in searchHistory" :key="index" @click="keyword = item; " :text="item"
						type="primary" plain class="history-tag"></uv-tags>
				</view>
				<view class="title">
					<text>热门搜索</text>
				</view>
				<view class="history-list">
					<uv-tags v-for="(item,index) in pageData.hotSearch" :key="index" @click="keyword = item; "
						:text="item" type="primary" plain class="history-tag"></uv-tags>
				</view>
			</view>

			<!-- 素材展示 -->
			<view v-if="pageData.searchStatus" class="m-data">
				<!-- 当搜索词，获取这搜索结果为空时 -->
				<view v-if="pageData.searchStatus && keyword == '' || !materialList.length " class="empty">
					<uv-empty mode="search" text="没有数据" />
				</view>

				<view class="waterfall">
					<uv-waterfall ref="waterfall" v-model="materialList" :columnCount="2" :add-time="10"
						:left-gap="pageData.leftGap" :right-gap="pageData.rightGap" :column-gap="pageData.columnGap"
						@changeList="changeList">
						<!-- 第一列数据 -->
						<template v-slot:list1>
							<!-- 为了磨平部分平台的BUG，必须套一层view -->
							<view>
								<view v-for="(item, index) in list1" :key="item.id" class="waterfall-item">
									<view class="waterfall-item__image" :style="[imageStyle(item)]"
										@click="onPreview(item)">
										<image :src="item.thumbnailUrl" mode="aspectFill"
											:style="{width:item.width+'px'}"></image>
									</view>
									<view class="waterfall-item__ft">
										<view class="waterfall-item__ft__title">
											<text class="value">{{item.materialTitle}}</text>
										</view>
										<view class="waterfall-item__ft__desc uv-line-2">
											<text class="value">{{item.desc}}</text>
										</view>
									</view>
								</view>
							</view>
						</template>

						<!-- 第二列数据 -->
						<template v-slot:list2>
							<!-- 为了磨平部分平台的BUG，必须套一层view -->
							<view>
								<view v-for="(item, index) in list2" :key="item.id" class="waterfall-item">
									<view class="waterfall-item__image" :style="[imageStyle(item)]"
										@click="onPreview(item)">
										<image :src="item.thumbnailUrl" mode="aspectFill"
											:style="{width:item.width+'px'}"></image>
									</view>
									<view class="waterfall-item__ft">
										<view class="waterfall-item__ft__title">
											<text class="value">{{item.materialTitle}}</text>
										</view>
										<view class="waterfall-item__ft__desc uv-line-2">
											<text class="value">{{item.desc}}</text>
										</view>
									</view>
								</view>
							</view>
						</template>

					</uv-waterfall>
					<!-- 加载状态提示 -->
					<view class="loading-status" v-if="materialList.length || !pageData.hasMore">
						<uv-load-more status="nomore" nomore-text="已经到底啦~" line lineColor="#e2e2e2" />
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted,
		reactive,
		watch
	} from "vue"
	import {
		onLoad,
		onReady,
		onPageScroll,
		onShow,
		onReachBottom
	} from "@dcloudio/uni-app"
	import {
		getKeywordList,
		searchMaterial
	} from "@/api/user.js"
	import {
		debounce
	} from "@/utils/common.js"

	// 搜索关键词
	const keyword = ref("")
	// 建议列表数据
	const suggestions = ref([])
	// 是否显示建议
	const showSuggestions = ref(false)
	// 历史搜索相关变量
	const searchHistory = ref([]) // 历史搜索列表

	const pageData = reactive({
		// 按钮内容
		btn_text: '搜索',
		// 素材展示相关
		leftGap: 10,
		rightGap: 10,
		columnGap: 10,
		loading: false,
		pageSize: 10,
		currentPage: 1,
		hasMore: true,
		// 搜索状态  是否展示搜索结果
		searchStatus: false,
		// 热门搜索
		hotSearch: ['搞笑', '你的名字']
	})
	// 素材列表
	const materialList = ref([])

	// 第一列数据
	const list1 = ref([])
	// 第二列数据
	const list2 = ref([])

	// 初始化时加载历史记录
	onLoad(() => {
		loadHistory()
	})

	onReachBottom(() => {
		handleReachBottom()
	})

	// 触底加载更多
	const handleReachBottom = debounce(async () => {
		console.log("触发触底了！");
		if (!pageData.hasMore || pageData.loading) return
		pageData.currentPage += 1
		await handleSearch();
	}, 300)

	// 从缓存加载历史记录
	const loadHistory = () => {
		try {
			const history = uni.getStorageSync('searchHistory') || []
			searchHistory.value = history.slice(0, 10) // 只取最新10条
			console.log("缓存历史记录：", searchHistory.value);
		} catch (e) {
			console.error('读取历史记录失败:', e)
		}
	}

	// 保存到历史记录（去重+最新在最前）
	const saveToHistory = (keyword) => {
		if (!keyword.trim()) return
		// set去重  限制10条
		searchHistory.value = [...new Set([keyword, ...searchHistory.value])].slice(0, 10)
		uni.setStorageSync('searchHistory', searchHistory.value)
	}

	// 清空历史记录
	const clearHistory = () => {
		searchHistory.value = []
		uni.removeStorageSync('searchHistory')
	}


	// 输入处理 关键词推荐
	const handleSearchInput = debounce(async () => {
		if (!keyword.value.trim()) {
			suggestions.value = []
			return
		}
		const params = {
			keyword: keyword.value
		}

		try {
			console.log("输入值：", keyword.value);
			await getKeywordList(params).then((res) => {
				// res.data可能不存在
				if (!res.data) {
					suggestions.value = []
					return
				}
				// 处理返回数据
				let temp = handleSuggestData(res.data);
				console.log("temp：", temp);
				suggestions.value = temp
			})
		} catch (e) {
			uni.showToast({
				title: res.msg || '数据加载失败',
				icon: 'none'
			})
			suggestions.value = []
		}

	}, 300)

	// 选择关键词
	const selectKeyword = (word) => {
		keyword.value = word
		showSuggestions.value = false
		// 执行搜索操作
		handleSearch()
	}

	// 失焦处理（避免点击建议项无法触发）
	const handleInputBlur = () => {
		setTimeout(() => {
			showSuggestions.value = false
		}, 200)
	}

	// 搜索素材
	const handleSearch = () => {
		// 对多次搜索的场景
		// if () {
		// 	materialList.value = []
		// 	keyword.value = ''
		// 	pageData.searchStatus = false
		// 	pageData.currentPage = 1
		// 	pageData.loading = false
		// 	pageData.hasMore = true
		// 	list1.value = []
		// 	list2.value = []
		// }

		pageData.searchStatus = true
		// 处理搜索功能
		if (!keyword.value.trim()) return
		saveToHistory(keyword.value)
		// 这里执行实际搜索逻辑...
		console.log('执行搜索:', keyword.value)
		try {
			pageData.loading = true
			let params = {
				materialTags: keyword.value,
				pageNum: pageData.currentPage,
				pageSize: pageData.pageSize
			}
			searchMaterial(params).then((res) => {
				if (res.code === 200 && res.rows) {
					// 处理接口数据
					const processedData = res.rows.map((item, index) => ({
						...item,
						w: 170, // 固定宽度
						h: 240 // 固定高度
					}))
					// 首次加载清空数据
					if (pageData.currentPage === 1) {
						materialList.value = processedData
					} else {
						materialList.value = [...materialList.value, ...processedData]
					}

					// 判断是否还有更多数据
					pageData.hasMore = res.rows.length >= pageData.pageSize
				} else if (res.code === 200 && res.rows === undefined || res.rows === null) {
					// 素材数是10的倍数时
					pageData.hasMore = false

				} else {
					uni.showToast({
						title: res.msg || '数据加载失败',
						icon: 'none'
					})
				}
			})
		} catch (error) {
			console.error('请求异常:', error)
			uni.showToast({
				title: '网络请求失败',
				icon: 'none'
			})
		} finally {
			pageData.loading = false
		}
	}


	// 处理推荐返回数据
	const handleSuggestData = (data) => {
		const results = new Set() // 用 Set 自动去重

		data.forEach(item => {
			// 处理标题：去除所有非文字符号  目前不能加这个。因为后端查询是从Tags中查询的,title中的不一定有。
			// const cleanTitle = extractPureText(item.materialTitle);
			// if (cleanTitle && cleanTitle.includes(keyword.value)) {
			// 	results.add(cleanTitle);
			// }

			// 处理标签：兼容数组/字符串格式，并深度清理
			const tags = parseTags(item.materialTags);
			tags.forEach(tag => {
				const cleanTag = extractPureText(tag);
				if (cleanTag && cleanTag.includes(keyword.value)) {
					results.add(cleanTag);
				}
			});
		});

		return Array.from(results);
	};


	// 核心函数：提取纯文本（去除所有非字母数字中日韩文字字符）
	const extractPureText = (str) => {
		if (typeof str !== 'string') return '';
		// 正则说明：匹配字母、数字、中日韩文字、空格（按需保留）
		return str.replace(/[^\w\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af\s]/g, '')
			.trim();
	};

	// 解析标签：兼容JSON字符串/数组/逗号分隔字符串
	const parseTags = (tags) => {
		try {
			// 如果已经是数组，直接返回
			if (Array.isArray(tags)) return tags;

			// 尝试解析为JSON数组（处理 "[...]" 格式）
			if (typeof tags === 'string' && tags.startsWith('[')) {
				return JSON.parse(tags.replace(/(\w+)/g, '"$1"')); // 修复非法JSON
			}

			// 处理普通逗号分隔字符串
			return tags.split(',').map(t => t.trim());
		} catch {
			return [];
		}
	};



	// 页面样式
	const imageStyle = (item) => {
		const v = uni.upx2px(750) - pageData.leftGap - pageData.rightGap - pageData.columnGap;
		const w = v / 2;
		const rate = w / item.w;
		const h = rate * item.h;
		return {
			width: w + 'px',
			height: h + 'px'
		}
	}

	// 列表数据变化
	const changeList = (e) => {
		console.log("changlist：", e);
		if (e.name === 'list1') {
			list1.value.push(e.value)
		} else {
			list2.value.push(e.value)
		}
	}

	// 点击素材处理
	const onPreview = (data) => {
		// 这里可以添加跳转逻辑
		uni.navigateTo({
			url: '/pages/preview/preview'
		})
		// 传递素材信息
		uni.setStorageSync("materialInfo", JSON.stringify(data))
	}
	// 清除输入值
	const clearKeyword = () => {
		materialList.value = []
		keyword.value = ''
		pageData.searchStatus = false
		pageData.currentPage = 1
		pageData.loading = false
		pageData.hasMore = true
		list1.value = []
		list2.value = []
	}

	// 监听输入值
	watch(keyword, (newValue, oldValue) => {
		if (newValue == null || newValue == '') {
			materialList.value = []
			keyword.value = ''
			pageData.searchStatus = false
			pageData.currentPage = 1
			pageData.loading = false
			pageData.hasMore = true
			list1.value = []
			list2.value = []
		}
	})
</script>

<style lang="scss" scoped>
	.layout {
		width: 100%;
		height: 100%;
		background-color: #f5f5f5;

		.top {
			width: 100%;
			height: 100rpx;
			background-color: #FFFFFF;
			padding: 0 20rpx;
			box-sizing: border-box;
			display: flex;
			align-items: center;
			/* 为列表定位 */
			position: relative;


			:deep(.uv-input) {
				border-radius: 1000px !important;

				transition: border 0.2s;

				&.is-focus {
					border: 2rpx solid #007AFF !important;

				}

				/* 强制圆形 */

				&:focus-within {
					box-shadow: 0 0 0 2rpx #007AFF !important; // 蓝色发光效果
				}
			}



			.search {
				width: 100%;
				height: 60rpx;
				border-radius: 30rpx;
				display: flex;
				align-items: center;

			}

			/* 下拉列表样式 */
			.suggest-list {
				position: absolute;
				top: 80rpx;
				left: 20rpx;
				right: 20rpx;
				background: #fff;
				border-radius: 16rpx;
				box-shadow: 0 4rpx 24rpx rgba(0, 0, 0, 0.1);
				z-index: 999;

				.suggest-item {
					padding: 24rpx 32rpx;
					font-size: 28rpx;
					color: #333;

					&:active {
						background: #f5f5f5;
					}

					&+.suggest-item {
						border-top: 1rpx solid #eee;
					}
				}
			}
		}

		.content {
			width: 100%;
			height: 100%;
			background-color: #FFFFFF;
			box-sizing: border-box;

			.title {
				width: 100%;
				height: 100rpx;
				display: flex;
				align-items: center;
				font-size: 30rpx;
				font-weight: bold;
				justify-content: space-between;
				align-items: center;
				padding: 20rpx 20rpx;

				.clear-btn {
					color: #999;
					font-size: 24rpx;
				}
			}

			.history-list {
				display: flex;
				flex-wrap: wrap;
				gap: 20rpx;
				padding: 20rpx 20rpx;

				.history-tag {
					background: #f5f5f5;
					border-radius: 40rpx;
					padding: 8rpx 24rpx;
				}
			}

			.m-data {
				width: 100%;
				padding: 20rpx 0;

				$show-lines: 1;
				@import '@/uni_modules/uv-ui-tools/libs/css/variable.scss';

				.waterfall-item {
					overflow: hidden;
					margin-top: 10px;
					border-radius: 6px;
				}

				.waterfall-item__ft {
					padding: 20rpx;
					background: #fff;
					backdrop-filter: blur(5px) brightness(90%);
					background-color: rgba(255, 255, 255, 0.5);
					border-radius: 10px;

					&__title {
						margin-bottom: 10rpx;
						line-height: 48rpx;
						font-weight: 700;
						text-align: center;

						.value {
							font-size: 32rpx;
							color: #303133;

						}
					}

					&__desc {
						text-align: center;

						.value {
							font-size: 28rpx;
							color: #606266;
						}
					}

					&__btn {
						padding: 10px 0;
					}
				}

				.loading-status {
					grid-column: 1 / -1;
					text-align: center;
					padding: 30rpx 0;
					font-size: 24rpx;
					color: #999;

					.no-more {
						display: block;
						padding-bottom: env(safe-area-inset-bottom);
					}
				}
			}
		}


	}
</style>